<?php
declare (strict_types = 1);

namespace app\v1\controller;

use app\BaseController;
use app\Request;
use app\model\User;
use app\v1\validate\Sms;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Validate;
use think\response\Json;

class SmsController extends BaseController
{
	protected $middleware = ['Login' => ['except' => ['send', 'check', '']]];
	
	
	/**
	 * 发送验证码
	 * event 验证码类型:登录=mobilelogin,注册=register,换绑手机号=changemobile,更改密码=changepwd,重置密码=resetpwd
	 * @return Json
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	function send(Request $request)
	{
		$params = $request->param();
		$event = $params['event'] ?? 'register';
		
		try {
			validate(Sms::class)->check($params);
		}catch (\Exception $e){
			writeJson(0,$e->getMessage());
		}
		$ipSendTotal = \app\v1\model\Sms::where(['ip' => $request->ip()])->whereTime('createtime', '-1 hours')->count();
		$last =  \app\v1\model\Sms::where(['mobile' => $params['mobile'], 'event' => $event])->order('id', 'DESC')->find();
		if (($last && time() - $last->createtime < 60)||$ipSendTotal >= 10) {
			writeJson(0,'发送频繁');
		}
		if ($event) {
			$userinfo = User::getByMobile($params['mobile']);
			if ($event == 'register' && $userinfo) {
				//已被注册
				writeJson(0,'已被注册');
			} elseif ($event == 'changemobile' && $userinfo) {
				//被占用
				writeJson(0,'已被占用');
			} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
				//未注册
				writeJson(0,'未注册');
			}
		}
		$ret = \app\common\Sms::send($params['mobile'], null, $event);
		if ($ret) {
			writeJson();
		} else {
			writeJson(0,'发送失败');
		}
	}

    /**
     * 检测验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ?? 'register';
        $captcha = $this->request->post("captcha");

        if (!$mobile || !Validate::regex($mobile, "^1\d{10}$")) {
	        writeJson(0,'手机号不正确');
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
	            writeJson(0,'已被注册');
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
	            writeJson(0,'已被占用');
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
	            writeJson(0,'未注册');
            }
        }
        $ret = \app\common\Sms::check($mobile, $captcha, $event);
        if ($ret) {
	        writeJson();
        } else {
	        writeJson(0,'验证码不正确');
        }
    }
}
